package com.yuang.filter;

import com.alibaba.fastjson.JSONObject;
import com.yuang.utils.RestTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SSOFilter implements Filter {
    public static Logger logger = LoggerFactory.getLogger(SSOFilter.class);
    private String SSO_SERVER_URL;
    private String SSO_SERVER_VERITFY_URL;

    public void init(FilterConfig filterConfig) throws ServletException {
        SSO_SERVER_URL = filterConfig.getInitParameter("SSO_SERVER_URL");
        SSO_SERVER_VERITFY_URL = filterConfig.getInitParameter("SSO_SERVER_VERITFY_URL");
        if(SSO_SERVER_URL == null) logger.error("SSO_SERVER_URL is null");
        if(SSO_SERVER_VERITFY_URL == null) logger.error("SSO_SERVER_VERITFY_URL is null");
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        //如果请求中带有token，就去sso-server中验证token是否有效
        String authority = null;
        if(request.getParameter("token") != null) {
            boolean verityResult =  this.verify(request,SSO_SERVER_VERITFY_URL,request.getParameter("token"));
            if(verityResult) {
                chain.doFilter(req,res);
                return;
            } else {
                authority = "token->"+request.getParameter("token")+"is invalidate.";
            }
        }

        //检查是否登录
        HttpSession session = request.getSession();
        if(session.getAttribute("login") != null && (Boolean)session.getAttribute("login") == true) {
            chain.doFilter(req,res);
            return;
        }

        //token无效，且又未登录，则跳转SSO认证中心
        String callbackURL = request.getRequestURI().toString();
        StringBuilder url =  new StringBuilder();
        url.append(SSO_SERVER_URL).append("&callbackURL=").append(callbackURL);
        if(authority!= null) {
            url.append("&authority=").append(authority);
        }
        response.sendRedirect(url.toString());
    }

    private boolean verify(HttpServletRequest request, String verifyUrl, String token) {
        String result = RestTemplateUtil.get(request,verifyUrl+"?token="+token,null);
        JSONObject ret = JSONObject.parseObject(result);
        if("success".equals(ret.getString("code"))) {
            return true;
        }
        logger.error(request.getRequestURI().toString()+":"+ret.getString("msg"));
        return false;
    }

    public void destroy() {

    }
}
